package com.reder.practice.service.impl;

import com.github.pagehelper.PageInfo;
import com.reder.practice.bean.LoginInfo;
import com.reder.practice.bean.User;
import com.reder.practice.bean.extend.LoginInfoExtend;
import com.reder.practice.bean.extend.UserExtend;
import com.reder.practice.common.dto.ServerResponse;
import com.reder.practice.common.enums.state.CommonState;
import com.reder.practice.common.enums.state.UserState;
import com.reder.practice.common.util.CodeUtil;
import com.reder.practice.common.util.PageUtil;
import com.reder.practice.common.util.SessionUtil;
import com.reder.practice.common.util.SqlResultUtil;
import com.reder.practice.dao.FollowerDao;
import com.reder.practice.dao.UserDao;
import com.reder.practice.service.UserService;
import com.reder.practice.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户业务实现类
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/09/06 11:36:31</p>
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao = null;

    @Resource
    private FollowerDao followerDao = null;

    @Resource
    private VideoService videoService;

    @Override
    public ServerResponse listUsers(int pageNumber, int sizeOfOnePage) {
        PageUtil.toPage(pageNumber, sizeOfOnePage);
        return ServerResponse.response(CommonState.SUCCESS, PageUtil.pageInfo(userDao.listUsers()));
    }

    // 如果 nickname 是空白的就会返回 true
    private boolean isNicknameAbsent(String nickname) {
        return CodeUtil.isBlank(nickname);
    }

    // 如果 nickname 和 password 两个中有一个是空白的就会返回 true
    private boolean isNicknameOrPasswordAbsent(String nickname, String password) {
        return isNicknameAbsent(nickname) || CodeUtil.isBlank(password);
    }

    // 返回参数不完整的响应
    private ServerResponse responseOfUncompletedParameter() {
        return ServerResponse.response(CommonState.PARAMETER_UNCOMPLETED);
    }

    @Override
    public ServerResponse register(String nickname, String password) {

        // 判断参数是否完整
        if (isNicknameOrPasswordAbsent(nickname, password)) {
            return responseOfUncompletedParameter();
        }

        // 检查用户昵称是否存在
        ServerResponse response = isNicknameExisted(nickname);
        if (!response.isSuccess()) {
            return response;
        }

        // 执行数据操作
        return SqlResultUtil.checkSqlResult(
                userDao.insertSelective(UserExtend.newUser(nickname, CodeUtil.md5(password))),
                UserState.REGISTER_FAILED
        );
    }

    @Override
    public ServerResponse isNicknameExisted(String nickname) {

        // 判断参数是否完整
        if (isNicknameAbsent(nickname)) {
            return responseOfUncompletedParameter();
        }

        int count = userDao.countByNickname(nickname);
        if (count > 0) {
            // 用户昵称已经存在
            return ServerResponse.response(UserState.NICKNAME_EXISTED);
        }

        // 用户昵称不存在
        return ServerResponse.response(CommonState.SUCCESS);
    }

    @Override
    public ServerResponse login(String nickname, String password) {

        // 判断参数是否完整
        if (isNicknameOrPasswordAbsent(nickname, password)) {
            return responseOfUncompletedParameter();
        }

        User user = userDao.selectByNickname(nickname);
        if (user == null) {
            return ServerResponse.response(UserState.NICKNAME_OR_PASSWORD_IS_INCORRECT);
        }

        if (CodeUtil.md5(password).equals(user.getPassword())) {
            // 用户名密码正确
            return ServerResponse.response(CommonState.SUCCESS, loginInfoOf(user));
        }
        return ServerResponse.response(UserState.NICKNAME_OR_PASSWORD_IS_INCORRECT);
    }

    // 将敏感信息屏蔽掉
    private void removeSensitiveInfo(User user) {
        if (user != null) {
            user.setPassword(null);
        }
    }

    // 包装用户登录信息
    private LoginInfo loginInfoOf(User user) {

        // 敏感信息不公开
        removeSensitiveInfo(user);

        // 装载用户 token 和用户信息
        return filledWithExtraInfo(LoginInfoExtend.newLoginInfo(user, SessionUtil.tokenOf(user)));
    }

    // 包装额外的信息
    private LoginInfo filledWithExtraInfo(LoginInfo info) {
        filledWithFollowUserIds(info);
        filledWithVideos(info);
        return info;
    }

    // 查询这个用户关注的用户 id
    private void filledWithFollowUserIds(LoginInfo info) {
        info.setFollowUserIds(followerDao.findByFollowerId(((User) info.getUser()).getId()));
    }

    // 查询第一页的视频
    @SuppressWarnings("unchecked")
    private void filledWithVideos(LoginInfo info) {
        ServerResponse<PageInfo> response = videoService.listVideo(1, PageUtil.DEFAULT_SIZE_OF_ONE_PAGE);
        info.setVideos(response.getData().getList());
    }

    @Override
    public ServerResponse getUser(long id) {

        // 查询并移除敏感信息
        User user = userDao.selectByPrimaryKey(id);
        if (user == null) {
            return ServerResponse.response(UserState.NICKNAME_OR_PASSWORD_IS_INCORRECT);
        }

        removeSensitiveInfo(user);
        return ServerResponse.response(CommonState.SUCCESS, user);
    }

    @Override
    public ServerResponse getUser(String nickname) {

        // 判断参数是否完整
        if (isNicknameAbsent(nickname)) {
            return responseOfUncompletedParameter();
        }

        // 查询并移除敏感信息
        User user = userDao.selectByNickname(nickname);
        if (user == null) {
            return ServerResponse.response(UserState.NICKNAME_OR_PASSWORD_IS_INCORRECT);
        }

        removeSensitiveInfo(user);
        return ServerResponse.response(CommonState.SUCCESS, user);
    }
}
